package com.example.fruitdemo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.fruitdemo.pojo.Category;
import com.example.fruitdemo.pojo.Good;
import com.example.fruitdemo.ruslet.R;
import com.example.fruitdemo.service.CategoryService;
import com.example.fruitdemo.service.GoodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/api/category")
public class CategoryController {
  @Autowired
  private   CategoryService categoryService;
  @Autowired
  private   GoodService goodService;
    @GetMapping("/list")
    public R<List> getlist(){
        List<Category> list = categoryService.list();
        return R.Ok(list);
    }
    //根据分类id获取名称
    @GetMapping("/getnamebyid/{id}")
    public R<String> getnameByid(@PathVariable("id") Long id){
        Category cate = categoryService.getById(id);
         return R.Ok( cate.getGoryname());
    }
    //根据searchname获取分类名称
    @GetMapping("/getnamebysearchname")
    public R<String> getnameBysearchname(String searchname){
        //先查出来商品的分类id
        LambdaQueryWrapper<Good> goodLambdaQueryWrapper=new LambdaQueryWrapper<>();
        goodLambdaQueryWrapper.like(searchname!=null,Good::getGoodname,searchname);
        List<Good> goods = goodService.list(goodLambdaQueryWrapper);
        Long cateid=goods.get(0).getGoryid();
        LambdaQueryWrapper<Category> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getId,cateid);
        Category cate = categoryService.getOne(queryWrapper);
        return R.Ok( cate.getGoryname());
    }
}
